package com.lancoo.cvas.aspect;

import com.lancoo.cvas.entity.TaskProcess;
import com.lancoo.cvas.pojo.constant.GlobalConstant;
import com.lancoo.cvas.pojo.dto.TaskProcessVo;
import com.lancoo.cvas.service.TaskInfoService;
import com.lancoo.cvas.service.TaskProcessService;
import com.lancoo.cvas.service.YunService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2019-07-09.
 */
@Component
@Aspect
@Slf4j
@Order(2)
public class MessageAnnotationAspect {

    @Autowired
    private HttpServletRequest request;

    @Resource
    @Lazy
    private YunService yunBasicService;
    @Resource
    @Lazy
    private TaskProcessService taskProcessService;


    @AfterReturning("@annotation(com.lancoo.cvas.aspect.MessageAnnotation)")
    public void afterReturning(JoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        MessageAnnotation logAnnotation = method.getAnnotation(MessageAnnotation.class);
        TaskProcessVo param = (TaskProcessVo) point.getArgs()[0];
        if (param.getFinish() != 1){
            return;
        }

        // 从请求头中获取参数
        String userId = request.getHeader("userId");
        String username = request.getHeader("userName");
        String taskId = request.getHeader("taskId");
        String schoolId = request.getHeader("schoolId");

        TaskProcess taskProcess = taskProcessService.lambdaQuery()
                .eq(TaskProcess::getTaskId, taskId)
                .eq(TaskProcess::getPower, param.getId()).one();

        // 获取注解参数
        String operationTerminal = logAnnotation.operationTerminal();
        String operationType = GlobalConstant.processOperationTypeMap.getOrDefault(taskProcess.getPower(), "2");
        String operationContent = taskProcess.getProcessName();


        yunBasicService.uploadLog(schoolId, userId, username, operationTerminal, operationType,
                operationContent, taskId);
    }


}